import { apiClient, type PaginatedResponse } from "./index";
import type { BookshelfItem } from "@/types";

export class BookshelfAPI {
  /**
   * 获取用户书架
   */
  static async getBookshelf(page = 1, limit = 20) {
    try {
      const response = await apiClient.get<PaginatedResponse<BookshelfItem>>(
        `/bookshelf?page=${page}&limit=${limit}`,
      );

      if (response.success && response.data) {
        return {
          success: true,
          data: response.data,
          message: response.message,
        };
      }

      return {
        success: false,
        data: [],
        message: response.message || "获取书架失败",
      };
    } catch (error) {
      return {
        success: false,
        data: [],
        message: (error as Error).message || "获取书架失败",
      };
    }
  }

  /**
   * 添加小说到书架
   */
  static async addToBookshelf(novelId: string) {
    try {
      const response = await apiClient.post(`/bookshelf/${novelId}`);

      return {
        success: response.success,
        message: response.message,
      };
    } catch (error) {
      return {
        success: false,
        message: (error as Error).message || "添加到书架失败",
      };
    }
  }

  /**
   * 从书架移除小说
   */
  static async removeFromBookshelf(novelId: string) {
    try {
      const response = await apiClient.delete(`/bookshelf/${novelId}`);

      return {
        success: response.success,
        message: response.message,
      };
    } catch (error) {
      return {
        success: false,
        message: (error as Error).message || "从书架移除失败",
      };
    }
  }

  /**
   * 更新阅读进度
   */
  static async updateReadingProgress(novelId: string, chapterId: string, progress?: number) {
    try {
      const response = await apiClient.put(`/bookshelf/${novelId}/progress`, {
        chapterId,
        progress: progress || 0,
      });

      return {
        success: response.success,
        message: response.message,
      };
    } catch (error) {
      return {
        success: false,
        message: (error as Error).message || "更新阅读进度失败",
      };
    }
  }

  /**
   * 设置收藏状态
   */
  static async toggleFavorite(novelId: string, isFavorite: boolean) {
    try {
      const response = await apiClient.put(`/bookshelf/${novelId}/favorite`, {
        isFavorite,
      });

      return {
        success: response.success,
        message: response.message,
      };
    } catch (error) {
      return {
        success: false,
        message: (error as Error).message || "设置收藏状态失败",
      };
    }
  }
}
